import bluebird from 'bluebird';
import moment from 'moment';
import db from '../db';
import log from '../../../log';
import * as util from '../../../util';

function create(queTemp, questions, options) {
    return db.exec(model => model('xp_questionnairetemplates').forge().save(queTemp, {method: 'insert'})
        .then(() => bluebird.reduce(questions, (total, item) => model('xp_questions').forge().save(item, {method: 'insert'}), 0))
        .then(() => bluebird.reduce(options, (total, item) => model('xp_questionoptions').forge().save(item, {method: 'insert'}), 0)));
}
function edit(id, queTemp, questionsOld, questionsNew, options) {
    return db.exec(model => model('xp_questionnairetemplates').forge({id}).save(queTemp, {method: 'update', require: false})
        .then(() => {
            return bluebird.reduce(questionsOld, (total, item) => model('xp_questionoptions').where({questionId: item.id}).drop(), 0);
        })
        .then(() => {
            return bluebird.reduce(questionsOld, (total, item) => model('xp_questions').forge({id}).save(item, {method: 'update', require: false}), 0);
        })
        .then(() => {
            return bluebird.reduce(questionsNew, (total, item) => model('xp_questions').forge().save(item, {method: 'insert'}), 0);
        })
        .then(() => {
            return bluebird.reduce(options, (total, item) => model('xp_questionoptions').forge().save(item, {method: 'insert'}), 0);
        })
    );
}
function updateStatus(id, status) {
    return db.get('xp_questionnairetemplates').forge({id}).save('status', status);
}
function del(id) {
    return db.get('xp_questionnairetemplates').forge({id}).save('isDel', 1);
}
/**
 * 返回所有的问卷列表
 */
function get(user, query, page, pageSize) {
    log.info('user:', user);
    const {title, status, id, isEnd} = query;
    const queTemp = db.get('xp_questionnairetemplates').forge();
    log.info('返回所有的问卷列表 ', ' page ', page);

    queTemp.query(qb => {
        qb.distinct('xp_questionnairetemplates.*');
        //统计参与人数
        const t1 = db._.raw('select count(1) from xp_questionnaires where xp_questionnaires.queTempId=xp_questionnairetemplates.id ').wrap('(', ') totalUser');
        qb.select(t1);
        qb.where('isDel', 0);
        if (user.username !== 'adm') {
            qb.where('createUserId', user.id);
        }
        if (title) {
            const liketitle = `%${title}%`;
            qb.where(function () {// eslint-disable-line
                this.where('xp_questionnairetemplates.title', 'like', liketitle)
                    .orWhere('xp_questionnairetemplates.subTitle', 'like', liketitle);
            });
        }
        if (id) {
            qb.where('xp_questionnairetemplates.id', id);
        }
        if (status) {
            qb.where('xp_questionnairetemplates.status', status);
        }
        if (isEnd !== undefined) {
            const operate = isEnd === '1' ? '<=' : '>';
            qb.where('dateEnd', operate, moment().format('YYYY-MM-DD HH:mm:ss'));
        }
        //qb.innerJoin('xp_questions', 'xp_questionnairetemplates.id', 'xp_questions.queTempId'); //过滤掉没有问题的问卷
        qb.orderBy('xp_questionnairetemplates.createTime', 'desc');
    });

    return queTemp.fetchPage({
        page,
        pageSize,
        withRelated: ['questions']
    });
}

function find(query, op) {
    return db.get('xp_questionnairetemplates').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('createTime');
    }).list({
        withRelated: ['questions']
    });
}

function getCountByUserId(userId) {
    return db.get('xp_questionnairetemplates').query(qb => {
        qb.where('createUserId', userId);
    }).count();
}

function getQueDetailsAndAnswers(queTempId, user) {
    log.info('获取问卷 ', ' queTempId: ', queTempId);
    return db.get('xp_questionnairetemplates').forge().query(qb => {
        qb.where({id: queTempId});
        //统计参与人数
        const t1 = db._.raw('select count(1) from xp_questionnaires where xp_questionnaires.queTempId=xp_questionnairetemplates.id ').wrap('(', ') totalUser');
        //统计总票数
        const t2 = db._.raw('select count(1) from xp_answers where xp_answers.queId in ( select id from xp_questionnaires where xp_questionnaires.queTempId=xp_questionnairetemplates.id )').wrap('(', ') total');
        qb.select('*', t1, t2);
    }).list({
        withRelated: ['questions', 'questions.options', 'questions.options.product']
    })
        .then(res => {
            res = res.toJSON() || [];
            res = res.length > 0 ? res[0] : {};
            return db.get('xp_questionnaires').where({queTempId, createUserId: user.id}).list()
                .then(que => {
                    que = que.toJSON() || [];
                    que = que.length > 0 ? que[0] : {};
                    return {...res, que};
                })
                .then(res => {
                    return bluebird.reduce(res.questions[0].options, (total, item) => {
                        return db.get('xp_answers').query(qb => {
                            qb.where('optionId', item.id);
                        }).count().then(r => {
                            item.statistics = r;
                            return r;
                        });
                    }, 0).then(() => {
                        return res;
                    });
                })
                .then(queTemp => {
                    //console.log('============= queTemp:', queTemp);
                    return queTemp;
                });
        });
}

export {create, edit, updateStatus, del, get, find, getCountByUserId, getQueDetailsAndAnswers};
